package com.college.eduService.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.college.eduService.entity.EduSubject;
import com.college.eduService.entity.excel.Subject;
import com.college.eduService.service.EduSubjectService;

//excel插入监听器
public class SubjectExcelListener extends AnalysisEventListener<Subject> {
    public EduSubjectService subjectService;

    public SubjectExcelListener() {
    }

    public SubjectExcelListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }

    //读取excel内容，一行一行读取
    @Override
    public void invoke(Subject subject, AnalysisContext analysisContext) {
        if(subject==null){
            throw new RuntimeException("文件数据为空");
        }
        //一级分类
        EduSubject existone = this.existone(subjectService, subject.getOneSubjectName());
        if(existone==null){//没有相同的一级分类就添加
            existone=new EduSubject();
            existone.setTitle(subject.getOneSubjectName());
            existone.setParentId("0");
            subjectService.save(existone);
        }
        //二级分类
        EduSubject existtwo = this.existtwo(subjectService, subject.getTwoSubjectName(),existone.getId());
        if(existtwo==null){//没有相同的二级分类就添加
            existtwo=new EduSubject();
            existtwo.setTitle(subject.getTwoSubjectName());
            existtwo.setParentId(existone.getId());
            subjectService.save(existtwo);
        }
    }

    //判断一级分类不能重复添加
    private EduSubject existone(EduSubjectService subjectService, String name){
        QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",0);
        EduSubject one = subjectService.getOne(wrapper);
        return one;
    }

    //判断二级分类不能重复添加
    private EduSubject existtwo(EduSubjectService subjectService,String name,String pid){
        QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject two = subjectService.getOne(wrapper);
        return two;
    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
